package com.example.opengldemo._01_;

import android.content.Context;
import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
import android.opengl.Matrix;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class MyTDView extends GLSurfaceView {
    final float ANGLE_SPAN = 0.375f ;
    RotateThread thread ;
    SceneRenderer mRenderer;

    public MyTDView(Context context) {
        super(context);
        this.setEGLContextClientVersion(3);
        mRenderer = new SceneRenderer();
        this.setRenderer(mRenderer);
        this.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }

    class SceneRenderer implements Renderer{
        Triangle triangle ;
        @Override
        public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
            GLES30.glClearColor(0,0,0,1) ;
            triangle = new Triangle(MyTDView.this) ;
            GLES30.glEnable(GLES30.GL_DEPTH_TEST);
            thread = new RotateThread() ;
            thread.start();
        }

        @Override
        public void onSurfaceChanged(GL10 gl10, int i, int i1) {
            GLES30.glViewport(0,0,i,i1); //设置视口
            float ratio = (float)i/i1 ;
            Matrix.frustumM(Triangle.mPMatrix , 0,-ratio,ratio,-1,1,1,10);
            Matrix.setLookAtM(Triangle.mVMatrix,0,0,0,3,0f,0f,0f,0f,1.0f,0.0f);
        }

        @Override
        public void onDrawFrame(GL10 gl10) {
            GLES30.glClear( GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);//清除颜色缓存和深度缓存
            triangle.drawSelf();
        }
    }

    class RotateThread extends Thread{
        public boolean flag=true;
        @Override
        public void run() {
            while (flag){
                mRenderer.triangle.xAngle = mRenderer.triangle.xAngle+ ANGLE_SPAN;
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
